/**
 * 头像生成工具
 * 支持多种方式生成用户头像
 */

// 预定义的颜色方案
const AVATAR_COLORS = [
  "#FF6B6B",
  "#4ECDC4",
  "#45B7D1",
  "#96CEB4",
  "#FFEAA7",
  "#DDA0DD",
  "#98D8C8",
  "#F7DC6F",
  "#BB8FCE",
  "#85C1E9",
  "#F8C471",
  "#82E0AA",
  "#F1948A",
  "#85C1E9",
  "#D7BDE2",
  "#A9DFBF",
  "#F9E79F",
  "#FADBD8",
  "#D5DBDB",
  "#AED6F1",
];

// 根据用户名生成稳定颜色
const getColorByUsername = (username: string): string => {
  let hash = 0;
  for (let i = 0; i < username.length; i++) {
    hash = username.charCodeAt(i) + ((hash << 5) - hash);
  }
  const index = Math.abs(hash) % AVATAR_COLORS.length;
  return AVATAR_COLORS[index];
};

// 生成随机颜色
export const getRandomColor = (): string => {
  return AVATAR_COLORS[Math.floor(Math.random() * AVATAR_COLORS.length)];
};

// 获取用户名的首字母
const getInitials = (username: string, maxLength: number = 2): string => {
  return username
    .split(" ")
    .map((word) => word.charAt(0))
    .join("")
    .toUpperCase()
    .substring(0, maxLength);
};

export interface AvatarOptions {
  size?: number;
  backgroundColor?: string;
  textColor?: string;
  bold?: boolean;
  rounded?: boolean;
  format?: "png" | "jpg" | "svg";
}

/**
 * 使用 ui-avatars.com 生成头像
 */
export const generateUIAvatar = (
  username: string,
  options: AvatarOptions = {}
): string => {
  const {
    size = 100,
    backgroundColor,
    textColor = "fff",
    bold = true,
    rounded = true,
    format = "png",
  } = options;

  const initials = getInitials(username);
  const bgColor = backgroundColor || getColorByUsername(username);

  const params = new URLSearchParams({
    name: initials,
    size: size.toString(),
    background: bgColor.replace("#", ""),
    color: textColor,
    bold: bold.toString(),
    format,
  });

  if (rounded) {
    params.append("rounded", "true");
  }

  return `https://ui-avatars.com/api/?${params.toString()}`;
};

/**
 * 使用 via.placeholder.com 生成头像
 */
export const generateViaAvatar = (
  username: string,
  options: AvatarOptions = {}
): string => {
  const { size = 100, backgroundColor, textColor = "FFFFFF" } = options;

  const initials = getInitials(username);
  const bgColor = backgroundColor || getColorByUsername(username);

  return `https://via.placeholder.com/${size}x${size}/${bgColor.replace(
    "#",
    ""
  )}/${textColor}?text=${initials}`;
};

/**
 * 使用 DiceBear API 生成头像
 */
export const generateDiceBearAvatar = (
  username: string,
  options: AvatarOptions = {}
): string => {
  const { size = 100, backgroundColor, format = "png" } = options;

  const bgColor = backgroundColor || getColorByUsername(username);

  const params = new URLSearchParams({
    seed: username,
    size: size.toString(),
    backgroundColor: bgColor.replace("#", ""),
    format,
  });

  return `https://api.dicebear.com/7.x/initials/${format}?${params.toString()}`;
};

/**
 * 使用 Gravatar 风格生成头像
 */
export const generateGravatarAvatar = (
  username: string,
  options: AvatarOptions = {}
): string => {
  const { size = 100, backgroundColor, textColor = "fff" } = options;

  const initials = getInitials(username);
  const bgColor = backgroundColor || getColorByUsername(username);

  const params = new URLSearchParams({
    s: size.toString(),
    d: `https://ui-avatars.com/api/?name=${initials}&size=${size}&background=${bgColor.replace(
      "#",
      ""
    )}&color=${textColor}&bold=true`,
  });

  return `https://www.gravatar.com/avatar/${btoa(
    username
  )}?${params.toString()}`;
};

/**
 * 默认头像生成器（推荐使用）
 */
export const generateAvatar = (
  username: string,
  options: AvatarOptions = {}
): string => {
  return generateUIAvatar(username, options);
};

/**
 * 批量生成头像
 */
export const generateAvatars = (
  usernames: string[],
  options: AvatarOptions = {}
): Record<string, string> => {
  const avatars: Record<string, string> = {};

  usernames.forEach((username) => {
    avatars[username] = generateAvatar(username, options);
  });

  return avatars;
};

/**
 * 获取头像颜色
 */
export const getAvatarColor = (username: string): string => {
  return getColorByUsername(username);
};

/**
 * 获取用户首字母
 */
export const getAvatarInitials = (username: string): string => {
  return getInitials(username);
};

// 导出所有颜色供外部使用
export { AVATAR_COLORS };
